package com.hexiang.config;

import com.alibaba.csp.sentinel.adapter.dubbo.fallback.DubboFallbackRegistry;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.springframework.context.annotation.Configuration;

/**
 * @author h01463
 * @version 1.0
 * @date 2024/8/7 19:45
 */
@Configuration
@Slf4j
public class DubboSentinelConfig {

    public DubboSentinelConfig(){
        DubboFallbackRegistry.setConsumerFallback((invoker, invocation, e) -> {
            String msg = "";
            if (e instanceof FlowException) {
                msg = "接口被限流";
            } else if (e instanceof BlockException) {
                msg = "接口被降级";
            } else if (e instanceof SystemBlockException) {
                msg = "系统繁忙";
            }
            log.error("使用参数{}调用服务{}的{}方法出现异常，具体原因是{}", invocation.getArguments(), invocation.getTargetServiceUniqueName(), invocation.getMethodName(), msg);

            return AsyncRpcResult.newDefaultAsyncResult(msg, invocation);
        });
    }
}
